﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace DetectiveCluedo
{
    public partial class NewGameForm : Form
    {
        public NewGameForm()
        {
            InitializeComponent();
        }

        private void loadPlayers()
        {
            clbPlayers.Items.Clear();

            foreach (string player in Properties.Settings.Default.Suspects.Split(','))
            {
                clbPlayers.Items.Add(CluedoGame.GetNameFromSuspectString(player));
            }
        }

        private void loadSelectPlayerPanel()
        {
            flowLayoutPanel1.Controls.Clear();

            foreach (string item in clbPlayers.CheckedItems)
            {
                flowLayoutPanel1.Controls.Add(new RadioButton() { Text = item.ToString() });
            }
        }

        private void loadYourCardsPanels()
        {
            flowLayoutPanelYourCardsSuspects.Controls.Clear();
            flowLayoutPanelYourCardsWeapons.Controls.Clear();
            flowLayoutPanelYourCardsRooms.Controls.Clear();

            flowLayoutPanelYourCardsSuspects.Controls.Add(new Label() { Text = "Suspects:" });
            foreach (string suspect in Properties.Settings.Default.Suspects.Split(','))
            {
                flowLayoutPanelYourCardsSuspects.Controls.Add(new CheckBox() { Text = CluedoGame.GetNameFromSuspectString(suspect), Tag = "Suspect" });
            }

            flowLayoutPanelYourCardsWeapons.Controls.Add(new Label() { Text = "Weapons:" });
            foreach (string weapon in Properties.Settings.Default.Weapons.Split(','))
            {
                flowLayoutPanelYourCardsWeapons.Controls.Add(new CheckBox() { Text = weapon, Tag = "Weapon" });
            }

            flowLayoutPanelYourCardsRooms.Controls.Add(new Label() { Text = "Rooms:" });
            foreach (string room in Properties.Settings.Default.Rooms.Split(','))
            {
                flowLayoutPanelYourCardsRooms.Controls.Add(new CheckBox() { Text = room, Tag = "Room" });
            }
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            CluedoGame.StartNewGame();
            loadPlayers();
            loadYourCardsPanels();
        }

        private void tabControl1_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (tabControl1.SelectedTab == tabPageSelectYourself)
            {
                loadSelectPlayerPanel();
            }

            buttonBack.Enabled = tabControl1.SelectedIndex > 0;
            buttonNext.Enabled = tabControl1.SelectedIndex < tabControl1.TabCount - 1;
            buttonStart.Enabled = tabControl1.SelectedIndex == tabControl1.TabCount - 1;
            //else if (tabControl1.SelectedTab == tabPageYourCards)
            //{
            //    loadYourCardsPanels();
            //}
        }

        private void buttonStart_Click(object sender, EventArgs e)
        {
            MDIParent1 f = (MDIParent1)this.Parent.Parent;

            var ggf = new GameGridForm();
            ggf.MdiParent = f;
            ggf.Show();

            var glf = new GameLogForm();
            glf.MdiParent = f;
            glf.Show();

            this.Close();

            f.LayoutMdi(MdiLayout.TileVertical);
        }

        private void buttonBack_Click(object sender, EventArgs e)
        {
            if (tabControl1.SelectedIndex > 0)
                tabControl1.SelectedIndex--;
        }

        private void buttonNext_Click(object sender, EventArgs e)
        {
            bool canProceed = true;

            if (tabControl1.SelectedTab == tabPagePlayers)
            {
                if (clbPlayers.CheckedItems.Count < 3)
                {
                    canProceed = false;
                    MessageBox.Show("Select at least three players!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
                else
                {
                    var p = clbPlayers.CheckedItems.Cast<string>().ToArray();
                    CluedoGame.CreatePlayers(p);
                }
            }

            else if (tabControl1.SelectedTab == tabPageSelectYourself)
            {
                bool isYouSelected = false;

                foreach (Control c in flowLayoutPanel1.Controls)
                {
                    if (c.GetType().IsAssignableFrom(typeof(RadioButton)))
                    {
                        if (((RadioButton)c).Checked)
                        {
                            isYouSelected = CluedoGame.SetYourself(((RadioButton)c).Text);
                        }
                    }
                }

                if (!isYouSelected)
                {
                    canProceed = false;
                    MessageBox.Show("Select yourself!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }

            else if (tabControl1.SelectedTab == tabPageYourCards)
            {
                //int checkedCardsCount = 0;
                List<Card> checkedCards = new List<Card>();

                foreach (Control c in flowLayoutPanelYourCardsSuspects.Controls)
                {
                    if (c.GetType().IsAssignableFrom(typeof(CheckBox)))
                    {
                        if (((CheckBox)c).Checked)
                            checkedCards.Add(new Card() { Name = ((CheckBox)c).Text, Type = (ECardType)Enum.Parse(typeof(ECardType), ((CheckBox)c).Tag.ToString(), true) });
                    }
                }
                foreach (Control c in flowLayoutPanelYourCardsWeapons.Controls)
                {
                    if (c.GetType().IsAssignableFrom(typeof(CheckBox)))
                    {
                        if (((CheckBox)c).Checked)
                            checkedCards.Add(new Card() { Name = ((CheckBox)c).Text, Type = (ECardType)Enum.Parse(typeof(ECardType), ((CheckBox)c).Tag.ToString(), true) });
                    }
                }
                foreach (Control c in flowLayoutPanelYourCardsRooms.Controls)
                {
                    if (c.GetType().IsAssignableFrom(typeof(CheckBox)))
                    {
                        if (((CheckBox)c).Checked)
                            checkedCards.Add(new Card() { Name = ((CheckBox)c).Text, Type = (ECardType)Enum.Parse(typeof(ECardType), ((CheckBox)c).Tag.ToString(), true) });
                    }
                }

                if (checkedCards.Where(c => c.Type == ECardType.Suspect).Count() == CluedoGame.Cards.Where(c => c.Type == ECardType.Suspect).Count())
                {
                    canProceed = false;
                    MessageBox.Show("At least one suspect must be in Confidential File!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }

                if (checkedCards.Where(c => c.Type == ECardType.Weapon).Count() == CluedoGame.Cards.Where(c => c.Type == ECardType.Weapon).Count())
                {
                    canProceed = false;
                    MessageBox.Show("At least one weapon must be in Confidential File!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }

                if (checkedCards.Where(c => c.Type == ECardType.Room).Count() == CluedoGame.Cards.Where(c => c.Type == ECardType.Room).Count())
                {
                    canProceed = false;
                    MessageBox.Show("At least one room must be in Confidential File!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }

                if (checkedCards.Count != CluedoGame.GetYourself().CardsCount)
                {
                    canProceed = false;
                    MessageBox.Show(string.Format("Select {0} cards ({1} {2})!"
                        , CluedoGame.GetYourself().CardsCount
                        , Math.Abs(checkedCards.Count - CluedoGame.GetYourself().CardsCount)
                        , (checkedCards.Count < CluedoGame.GetYourself().CardsCount) ? "more" : "less"), "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }


                if (canProceed)
                {
                    foreach (Card card in checkedCards)
                    {
                        CluedoGame.SetPlayersCardInfo(CluedoGame.GetYourself(), card, true, EPlayerCardInfoStatusReason.MyCard);
                    }
                }
            }


            if (canProceed && tabControl1.SelectedIndex < tabControl1.TabCount - 1)
                tabControl1.SelectedIndex++;


            if (tabControl1.SelectedTab == tabPageSummary)
            {
                StringBuilder sb = new StringBuilder();
                sb.AppendLine("GAME SUMMARY");
                sb.AppendLine("");
                sb.AppendLine("Players:");
                foreach (Player p in CluedoGame.Players)
                {
                    sb.AppendLine(" - " + p.Name + ((p.IsYou) ? " (You)" : ""));
                }

                sb.AppendLine("");
                sb.AppendLine("Your cards:");
                foreach (PlayerCardInfo pci in CluedoGame.GetPlayerCardInfoLog().Where(c => c.Reason == EPlayerCardInfoStatusReason.MyCard))
                {
                    sb.AppendLine(" - " + pci.Card.Name + " [" + pci.Card.Type.ToString() + "]");
                }
                richTextBoxSummary.Text = sb.ToString();
            }
        }

        private void tabPageYourCards_Resize(object sender, EventArgs e)
        {
            flowLayoutPanelYourCardsSuspects.Width = this.Width / 3;
            flowLayoutPanelYourCardsWeapons.Width = this.Width / 3;
            flowLayoutPanelYourCardsRooms.Width = this.Width / 3;
        }

        private void buttonMoveUp_Click(object sender, EventArgs e)
        {
            if (clbPlayers.SelectedIndex > 0)
                reorder(clbPlayers.SelectedIndex, clbPlayers.SelectedIndex - 1);
        }

        private void buttonMoveDown_Click(object sender, EventArgs e)
        {
            if (clbPlayers.SelectedIndex >= 0 && clbPlayers.SelectedIndex < clbPlayers.Items.Count - 1)
                reorder(clbPlayers.SelectedIndex, clbPlayers.SelectedIndex + 1);
        }

        private void reorder(int idx1, int idx2)
        {
            string s1 = clbPlayers.Items[idx1].ToString();
            string s2 = clbPlayers.Items[idx2].ToString();

            bool ckd1 = clbPlayers.GetItemChecked(idx1);
            bool ckd2 = clbPlayers.GetItemChecked(idx2);

            int si = clbPlayers.SelectedIndex;

            clbPlayers.Items[idx1] = clbPlayers.Items[idx2];
            clbPlayers.Items[idx2] = s1;

            clbPlayers.SetItemChecked(idx1, ckd2);
            clbPlayers.SetItemChecked(idx2, ckd1);

            clbPlayers.SelectedIndex = si + (idx2 - idx1);
        }

        

    }
}
